package linked_list;

public class 训练计划5 {
      public class ListNode {
      int val;
     ListNode next;
      ListNode(int x) {
          val = x;
         next = null;
      }
  }

    public class Solution {
            public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            int lena = 0, lenb = 0;
            ListNode a = headA, b = headB;

            while(a != null){
                lena++;
                a = a.next;
            }

            while(b != null){
                lenb++;
                b = b.next;
            }

            int d = lena - lenb;

            if(d > 0){
                while(d-- > 0)
                    headA = headA.next;
            }else if(d < 0){
                d = -d;
                while(d-- > 0)
                    headB = headB.next;
            }

            while(headA != headB){
                headA = headA.next;
                headB = headB.next;
            }
            return headA;
        }
    }
    public class Solution2{
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            ListNode A = headA,B=headB;
            while (A!=B){
                A = A!=null ? A=A.next : headB;
                B = B!=null ? B=B.next : headA;
            }
            return A;
        }
    }

}
